#include "socket.hpp"
#include "server.hpp"
#include <pthread.h>

void Usage(const std::string& proc)
{
    std::cout << "Usage: " << proc << " port" << std::endl;
}

void* handle(void* arg)
{
    // 线程分离
    pthread_detach(pthread_self());
    int sock = *(int*)arg;
    Server svr;
    for (;;)
    {
        svr.readData(sock);
    }
    return NULL;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    // 创建socket
    int listen_sock = Sock::Socket();
    // 设置端口复用
    int opt = 1;
    setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    // 绑定端口
    Sock::Bind(listen_sock, atoi(argv[1]));
    // 监听
    Sock::Listen(listen_sock);
    // 初始化MySQL
    Util::initMysql();
    // 等待客户端到来
    for (;;)
    {
        int sock = Sock::Accept(listen_sock);
        // 业务逻辑
        pthread_t tid;
        pthread_create(&tid, NULL, handle, (int*)&sock);
    }

    return 0;
}